<template>
  <div class="bg_block">
    <div class="index_top">
      <div class="top_logo">
        <img :src="requireImg('02.png')" alt="">
      </div>

      <div class="top_box">
        <div class="top_item">
          <div class="top_item_name">比特币参与总量</div> 
          <div class="top_item_value">{{ store.state.cumulativeBtcb }} BTC</div>
        </div>
        <div class="top_item">
          <div class="top_item_name">已产出比特圣经</div> 
          <div class="top_item_value">{{ store.state.produceBB }} BB</div>
        </div>
        <div class="top_item">
          <div class="top_item_name">我当前的持仓数量</div> 
          <div class="top_item_value">{{ store.state.userInfo.lockBtcb }}  BTC</div>
        </div>
        <div class="top_item">
          <div class="top_item_name">我获得的比特圣经</div> 
          <div class="top_item_value">{{ store.state.userInfo.bb }} BB</div>
        </div>
        <div class="top_item">
          <div class="top_item_name">我的参与成本</div> 
          <div class="top_item_value">{{ store.state.userInfo.usdt }}  USDT</div>
        </div>
        <div class="top_item">
          <div class="top_item_name">我的盈利</div> 
          <div class="top_item_value">{{ store.state.userInfo.profit }}  USDT</div>
        </div>
      </div>

      <div class="top_bottom">
      <div class="top_bottom_title">
          <i class="iconfont icon-lingxing"></i>
        勋章显示
      
        <i class="iconfont icon-lingxing"></i></div>    
      <img :src="requireImg('04.png')" alt="">
      <div class="top_bottom_title">聪者</div>
    
      </div>
      
      
    </div>
    <div class="index_center light_border">
        <div class="index_title">标题
          <van-checkbox class="index_title2" v-model="isSend" checked-color="#1bbc64"> 赠送他人</van-checkbox>
        </div>
        <div class="cell field_background theme_color">
          <van-field v-model="formData.title"   clearable   :placeholder="t('请输入标题')"></van-field>
        </div>
        <template v-if="isSend">
        <div class="index_title">赠送者地址
            <van-checkbox class="index_title2" v-model="isOwner" checked-color="#1bbc64">保留赎回权限</van-checkbox>
        </div>
        <div class="cell field_background theme_color">
          <van-field class="address_class" v-model="formData.receiveAddress"    clearable   :placeholder="t('请输入地址')">
            <template #button>
              <scan @change="getScanData"></scan>
            </template>
          </van-field>
        </div>
      </template>
        <!-- <van-checkbox class="index_title2" v-model="checked" checked-color="#1bbc64">释放规则</van-checkbox> -->
        <div class="index_title">释放规则  </div>
        <!-- <div class="index_title2"> <i class="iconfont icon-a-ic_CompleteSelect"></i> 释放规则</div> -->
        <div class="rule_box light_border">
          <div class="rule_item">
            <div class="rule_name">
              首次释放日期
            </div>
            <div class="cell field_background theme_color">
              <van-field @click="openDataPicker" v-model="formData.tgeDate" readonly   clearable   :placeholder="t('')"></van-field>
            </div>
          </div>

     

          <div class="rule_item">
            <div class="rule_name">
              首次释放百分比（%）
            </div>
            <div class="cell field_background theme_color">
              <van-field v-model="formData.tgeBps" type="number"  clearable   :placeholder="t('')"></van-field>
            </div>
          </div>
          <template v-if="formData.tgeBps!=100">

          <div class="rule_item">
            <div class="rule_name">
              循环释放间隔（天）
            </div>
            <div class="cell field_background theme_color">
              <van-field v-model="formData.cycle" type="number"   clearable   :placeholder="t('')"></van-field>
            </div>
          </div>

          <div class="rule_item">
            <div class="rule_name">
              循环释放百分比（%）
            </div>
            <div class="cell field_background theme_color">
              <van-field v-model="formData.cycleBps" type="number"   clearable   :placeholder="t('')"></van-field>
            </div>
          </div>
        </template>

        </div>
        <div class="index_title">感恩释放接收者推荐人地址</div>
        <div class="cell field_background theme_color">
          <div class="invited_address2 address_class" v-if="store.state.myParent&&!isSend">
          {{ splitAddress(store.state.myParent,9) }}
          </div>
          <van-field v-else class="address_class" v-model="formData.referenceAddress"    clearable   placeholder="">
            <template #button>
              <scan @change="getScanData"></scan>
            </template>
          </van-field>
        </div>

        <div class="index_title">感恩比例（%）</div>
        <div class="cell field_background theme_color">
          <van-field class="address_class" v-model="formData.referenceRatio" type="number"    clearable   placeholder=""></van-field>
        </div>

        <div class="index_title">备注</div>
        <div class="cell field_background theme_color">
          <van-field class="address_class"  rows="4" autosize v-model="formData.remark" type="textarea"    clearable   :placeholder="t('请输入备注...')"></van-field>
        </div>

    </div>
    <div class="index_token">
      <usdtIcon @click="isBuy=true" :isActive="isBuy"></usdtIcon>
      <btcIcon @click="isBuy=false" :isActive="!isBuy"></btcIcon>
    </div>

    <div class="index_bottom light_border">
      <div class="bottom_title">
        我要锁仓数量
      </div>
      <div>
        <div class="bottom_field field_background theme_color">
              <van-field v-model="formData.amount" type="number"  clearable   :placeholder="t('请输入锁仓数量...')"></van-field>
            </div>
      </div>
      <div class="bottom_tabs">
        <div class="bottom_item" @click="setAmount(item)"  v-for="item in chooseAmountArr" :key="item.value">
          {{item.name}}
        </div>
      </div>


    </div>


    <div class="top10">
      <div class="my_value_box">
        <div class="my_value_title"> {{ t('myValue') }} ：</div>
        <div class="my_value_number" v-if="isBuy"> {{ store.state.usdtBalance }} {{ store.state.USDT}}</div>
        <div class="my_value_number" v-else> {{ store.state.btcBalance }} {{ store.state.BTC}}</div>
      </div>
      <van-button :loading="loading" class="confirm_btc"  @click="confirm" type="primary">
        {{ t('确认') }}
      </van-button>
    </div>

    <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
      <van-picker-group
  title="首次释放日期"
  :tabs="['选择日期', '选择时间']"
  next-step-text="下一步"
  @confirm="onConfirm"
  @cancel="onCancel"
>
  <van-date-picker
    v-model="currentDate"
    :min-date="minDate"
    :max-date="maxDate"
  />
  <van-time-picker :columns-type="['hour', 'minute', 'second']" v-model="currentTime" />
</van-picker-group>
</van-popup>
  </div>
</template>
<script setup>
import { showToast } from "vant";
import IndexDBCache from '@/hooks/sql/useOrder.js'
const orderDB = new IndexDBCache()
import bus from "@/utils/bus.js"
import "vant/es/toast/style";
import { useStore } from "vuex";
import { ethers } from "ethers";
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import bankEth from "@/utils/bankEth.js";
import eth from "@/utils/eth.js";
const { locale, t } = useI18n();
import { splitAddress } from "@/utils/index.js";
import { useRouter } from "vue-router";
import { usdtContract,bankContract, btcContract } from "../../utils/config";
import { getDate } from "../../utils";
const requireImg = (imgPath) => {
  return new URL(`../../assets/images/${imgPath}`, import.meta.url).href;
};
const isOwner = ref(false)
const isSend = ref(false)
const isBuy = ref(false)
const chooseAmountArr = computed(()=>{
  return [
    {name:'最小',value:1},
    {name:'1/2',value:2},
    {name:'最大',value:3},
  ]
})
const setAmount = (item)=>{
  if(item.value==1) {
    formData.value.amount = 100
  }else if(item.value==2){
    if(isBuy.value){
      formData.value.amount = store.state.usdtBalance/2
    }else{
      formData.value.amount = store.state.btcBalance/2
    }
  }else{
    if(isBuy.value){
      formData.value.amount = store.state.usdtBalance
    }else{
      formData.value.amount = store.state.btcBalance
    }
  }
}
const showPicker = ref(false)
const  minDate = ref(new Date(2024, 1, 1)) 
const  maxDate = ref(new Date(2035, 5, 1))
const currentDate = ref(['2025', '06', '01']);
const currentTime = ref(['12', '00', '00']);
const disabledBtn = ref(false)
const tenTime = ref(0)
const router = useRouter();
const store = useStore();
const loading =  ref(false);
const formData = ref({
  name:'',
  receiveAddress:'',
  referenceAddress:'',
  tgeDate:'',
  cycleBps:'',
  

})
const onConfirm = (value)=>{

  let data = currentDate.value.join('-') + ' ' + currentTime.value.join(':')
  formData.value.tgeDate = data
  showPicker.value = false
  
}
const onCancel = (value)=>{
  showPicker.value = false
}
const getScanData = (value)=>{
  formData.value.receiveAddress = value
}
const openDataPicker = ()=>{
  showPicker.value = true
}
const goToPage = (value, type) => {
  let query = {
  };
  router.push({
    name: value,
    query,
  });
};
const getInvite = () => {
  formData.value.referenceAddress =  router.currentRoute.value.query.referrer || ''
}
const timeId = ref()
const initData = async ()=>{
  eth.getUsdtAndBtc()
}
const confirm = async ()=>{
  if(!store.state.myParent){
    // 没填邀请人
    if(!formData.value.referenceAddress){
      showToast(t('pleaseEnterInviter'))
      return 
    } 
  }
    if(formData.value.amount<=0){
      showToast(t('pleaseEnterAmount'))
      return 
    }

  loading.value = true
  try {
    let allowance = await eth.getAllowance(btcContract[0], bankContract,btcContract[3]);
    if (Number(formData.value.amount) > Number(allowance)) {
      await eth.approve(
        Number(formData.value.amount),
        btcContract[0],
        bankContract,
        btcContract[3]
      );
      // 授权
    }
    let amount = ethers.utils.parseUnits(String( Number(formData.value.amount)),  btcContract[3]);
    let tgeDate = 0
    const dateObj = new Date(formData.value.tgeDate); // 转换为 Date 对象
  if (isNaN(dateObj.getTime())) {
  console.log("无效日期格式");
  } else {
     const timestampMs = dateObj.getTime(); // 毫秒时间戳
     tgeDate = Math.floor(timestampMs / 1000); // 转换为秒
     console.log(tgeDate); // 输出：1696163400（秒）
  }
    let data = [
    // 接收地址
    isSend.value ?   formData.value.receiveAddress: store.state.address,
    // 邀请地址
    formData.value.referenceAddress||store.state.myParent,
    // 邀请比例
    ethers.utils.parseUnits(String( Number(formData.value.referenceRatio)),2),
    // 数量
    amount,
    // 是否保留
    isOwner.value?'1':0,
    // 首次时间
    tgeDate,
    // 首次比例
    ethers.utils.parseUnits(String(Number(formData.value.tgeBps)),2),
    // 循环间隔天数
    formData.value.cycle,
    //循环释放百分比
    ethers.utils.parseUnits(String(Number(formData.value.cycleBps)),2),
    // 是否用usdt买btc
    isBuy.value,
    // 描述备注
    formData.value.remark,
    // 标题
    formData.value.title,
    ]
    let hex = null
    // 单个锁
    if(formData.value.tgeBps==100){
       data.splice(6,3)
       hex = await  bankEth.ContractWithSinger.lock(...data)
    }else{
      // 循环锁
      hex = await  bankEth.ContractWithSinger.vestingLock(...data)

    }
    // 循环锁
   await hex.wait();
   loading.value = false;
   showToast(t('createSuccess'))
   initData()

  } catch (error) {
    let errorStr = JSON.stringify(error)
    if(errorStr&&errorStr.indexOf("Please change the recommender")>=0){
      showToast(t('recommenderIsWrong'))
    }
    else{
      if(store.state.isShowError){
        showToast(t('createFail')+errorStr)
      }else{
        showToast(t('createFail'))
      }
    } 
    loading.value = false;
  }
  

}
const fn = ()=>{
  bus.on("init",(value)=>{
    initData()
  })
}
onUnmounted(()=>{
  bus.off("init")
})
onMounted(() => {
  initData();
  getInvite()
  fn()
});
</script>
<style>
.order_list{
  min-height: 80px;
}
:root:root {
  --van-button-primary-background: #f39018;
  --van-pagination-item-default-color: #f39018;
}
</style>
<style lang="scss" scoped>
.field_background{
  // border: 1px solid $primary-color !important;
}
.address_class{
  font-size: 10px;
}
.invited_address2{
  padding:10px 6px;

}
.bg_block{
  margin-top: 44px;
  padding: 16px 14px 30px 14px;
  box-sizing: border-box;
  background-position: 0 100px;
  background-size: 100% auto;
}
.index_top{
  border-radius: 6px;
  margin-top:45px;
  min-height: 200px;
  background: url(../../assets/images/03.png) no-repeat;
  background-size: 100% 100%;
  padding: 10px 10px 14px 10px;
  position: relative;
  .top_logo{
    position: absolute;
    left: 50%;
    top:-50px;
    height:100px;
    width:100px;
    transform: translateX(-50%);
    img{
      height:100%;
      width:100%;
    }
  }
  .top_box{
    display: flex;
    flex-wrap: wrap;
    gap:10px;
    padding-top: 60px;
    .top_item{
      border-radius: 5px;
      width: calc(50% - 5px);
      box-sizing: border-box;
      padding: 6px;
      border: 1px solid $primary-color;
      .top_item_name{
        color: #eee;
      }
      .top_item_value{
        line-height: 20px;
        color: $primary-color;
      }
    }
  }
  .top_bottom{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    .top_bottom_title{
      color: #eee;
      display:flex;
      align-items: center;
      gap: 5px;
      i{
        color: $primary-color;
        font-size: 10px;
      }
    }
    img{
      margin:6px;
      height: 40px;
      width: 40px;
    }

  }
}
.index_center{
  margin-top: 14px;
  border-radius: 6px;
  padding: 10px;
  .index_title{
    font-weight: bold;
    color: #000;
    font-size: 10px;
    display: flex;
    height: 24px;

    align-items: center;
    justify-content: space-between;
  }
  .index_title2{
    height: 24px;
    font-weight: 500;
    display: flex;
    color: $primary-color;
    line-height: 24px;
    align-items: center;
    :deep .van-checkbox__icon{
      font-size: 14px;
    }
    :deep .van-checkbox__label{
      color: $primary-color;
      line-height: normal;
    }
    i{
      font-size: 12px !important;
      color: #1bbc64;
    }
  }
  .rule_box{
    border-radius: 5px;
    padding: 6px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .rule_item{
      display: flex;
      flex-direction: column;
      width: calc(50% - 5px);
      .rule_name{
          line-height: 20px;
      } 
    }
  }
  .cell{
    border-radius: 5px;
    :deep .van-field{
      padding: var(--van-cell-vertical-padding) 8px;
    }
    :deep .van-icon{
      height: 12px;
      font-size: 14px;
    }
  }
}
.index_token{
  margin-top: 14px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  .token_item{
    border-radius: 16px;
    padding: 6px 16px;
    background: #cecece;
    color: #888;
  }
  .token_item_active{
    background: $primary-color;
    color: #fff;
  }
}
.index_bottom{
  margin-top: 6px;
  border-radius: 6px;
  padding: 10px;
  .bottom_title{
    font-weight: bold;
    text-align: center;
  }
  .bottom_field{
    border-radius: 5px;
    width:200px;
    margin:10px auto;
    :deep .van-field{
      padding: 8px;
    }
  }
  .bottom_tabs{
    width: 200px;
    margin: auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .bottom_item{
      border-radius: 20px;
      color: #888;
      padding: 4px 6px;
      min-width: 40px;
      text-align: center;
      border: 1px solid #bbb;
    }
   
  }
}
.my_value_box{
  display: flex;
  align-items: center;
  justify-content: center;
  color: $primary-color;

}
.confirm_btc{
  border-radius: 20px;
  margin-top: 8px;
  height: 34px;
}
</style>
